package com.bolingcavalry.crm.serviceorder.service.Impl;/*
 * @Auther:Sadie
 * @Date:2025/4/24
 * @Description:
 * @VERSON:1.8
 */

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.base.ResponseResult;
import com.base.RoleEnum;
import com.base.Status;
import com.bolingcavalry.crm.aftersales.mapper.AfterSalesMapper;
import com.bolingcavalry.crm.message.config.RabbitMQConstants;
import com.bolingcavalry.crm.product.mapper.ProductMapper;
import com.bolingcavalry.crm.receiver.mapper.ReceiverMapper;
import com.bolingcavalry.crm.serviceorder.mapper.ServiceOrderMapper;
import com.bolingcavalry.crm.serviceorder.mapper.ServiceOrderProductMapper;
import com.bolingcavalry.crm.serviceorder.service.ServiceOrderService;
import com.bolingcavalry.crm.recyclebin.mapper.RecyclebinMapper;
import com.bolingcavalry.crm.recyclebin.service.OrderRestoreService;
import com.bolingcavalry.crm.security.utils.SecurityUtils;
import com.bolingcavalry.crm.taskorder.mapper.TaskorderMapper;
import com.bolingcavalry.crm.taskorder.service.ConfirmationService;
import com.bolingcavalry.crm.taskorder.service.TaskorderService;
import com.dto.ProductDTO;
import com.dto.ServiceOrderDTO;
import com.dto.TaskOrderDTO;
import com.dto.TaskReviewMessageDTO;
import com.entity.product.Product;
import com.entity.receiver.Receiver;
import com.entity.serviceorder.ServiceOrder;
import com.entity.serviceorder.ServiceOrderProduct;
import com.bolingcavalry.crm.utils.AUtils;
import com.entity.recyclebin.RecycleBinOrder;
import com.vo.ProductVO;
import com.vo.ServiceOrderVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.hibernate.service.spi.ServiceException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Slf4j
@Service(Status.SERVICE_ORDER)
public class ServiceOrderServiceImpl implements ServiceOrderService, OrderRestoreService {
    @Autowired
    private ServiceOrderMapper serviceOrderMapper;
    @Autowired
    private ServiceOrderProductMapper serviceOrderProductMapper;
    @Autowired
    private AUtils aUtils;
    @Autowired
    private RecyclebinMapper recyclebinMapper;
    @Autowired
    private TaskorderService taskorderService;
    @Autowired
    private ConfirmationService confirmationService;
    @Autowired
    private TaskorderMapper taskorderMapper;
    @Autowired
    private ReceiverMapper receiverMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private AfterSalesMapper afterSalesMapper;

    /**
     * 新增服务单
     * @param serviceOrderDTO
     * @return
     */
    @Override
    @Transactional
    public Boolean add(ServiceOrderDTO serviceOrderDTO) {
        log.info("add service order收到消息: " + serviceOrderDTO);
        // 校验服务单号是否重复
        if (serviceOrderDTO.getServiceOrderNumber() != null) {
            if (serviceOrderMapper.selectByServiceOrderNumber(serviceOrderDTO.getServiceOrderNumber())) {
                throw new RuntimeException("服务单号已存在，禁止重复添加");
            }
        }
        ServiceOrder serviceOrder = new ServiceOrder();
        // 拷贝属性
        BeanUtils.copyProperties(serviceOrderDTO,serviceOrder);
        // 获取客户公司ID
        Long customerCompanyId = null;
        if (serviceOrderDTO.getCustomerCompany() != null) {
            customerCompanyId = aUtils.getCustomerCompanyId(serviceOrderDTO.getCustomerCompany());
        }

        // 处理联系人信息
        String contactPerson = null;
        String phoneNumber = null;
        Long contactPersonId = null;
        if (serviceOrderDTO.getContactPerson() != null) {
            contactPerson = serviceOrderDTO.getContactPerson();
            phoneNumber = serviceOrderDTO.getPhoneNumber();
            contactPersonId = aUtils.getcontactPersonId(contactPerson, phoneNumber, customerCompanyId);
        }

        // 销售经理ID
        Long salesManagerId = null;
        if (serviceOrderDTO.getSalesManager() != null) {
            salesManagerId = aUtils.getUserIdByNickName(serviceOrderDTO.getSalesManager());
        }

        // 技术对接人ID
        Long technicalUserId = null;
        if (serviceOrderDTO.getTechnicalUser() != null) {
            technicalUserId = aUtils.getUserIdByNickName(serviceOrderDTO.getTechnicalUser());
        }

        // 工作量核准人ID
        Long approverUserId = null;
        if (serviceOrderDTO.getApproverUser() != null) {
            approverUserId = aUtils.getUserIdByNickName(serviceOrderDTO.getApproverUser());
        }

        //如果接收时间存在需要转为时间戳
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        if(serviceOrderDTO.getReceiveTime()!=null && !serviceOrderDTO.getReceiveTime().trim().isEmpty()){
            LocalDate date = LocalDate.parse(serviceOrderDTO.getReceiveTime(), formatter);
            serviceOrder.setReceiveTime(date);
            // 手动处理时间字段格式化以便后续存入excel
            serviceOrderDTO.setReceiveTime(serviceOrderDTO.getReceiveTime().replace("-", "/"));
        }
        else{
            serviceOrder.setReceiveTime(LocalDate.now());
        }
        //如果签收时间存在需要转为时间戳
        if(serviceOrderDTO.getConfirmSignDate()!=null){
            LocalDate date = LocalDate.parse(serviceOrderDTO.getConfirmSignDate(), formatter);
            serviceOrder.setConfirmSignDate(date);
            serviceOrderDTO.setConfirmSignDate( serviceOrderDTO.getConfirmSignDate().replace("-", "/"));
        }
        // 设置实体属性
        serviceOrder.setCustomerCompanyId(customerCompanyId);
        serviceOrder.setCustomerContactsId(contactPersonId);
        serviceOrder.setSalesManagerId(salesManagerId);
        serviceOrder.setTechnicalUserId(technicalUserId);
        serviceOrder.setApproverUserId(approverUserId);
        serviceOrder.setCreatedBy(aUtils.getNickNameByuserName(SecurityUtils.getCurrentUsername()));
        serviceOrder.setCreateTime(LocalDateTime.now());
        serviceOrder.setUpdateTime(LocalDateTime.now());

        try {
            serviceOrderMapper.insert(serviceOrder);
        } catch (Exception e) {
            throw new RuntimeException("服务单新增失败", e);
        }

        // 插入配件信息
        if (serviceOrderDTO.getProducts() != null) {
            for (ProductDTO dto : serviceOrderDTO.getProducts()) {
                if(dto.getName().isEmpty()){
                    continue;
                }
                //获取价格和数量可以为空，因为通知单不知道使用多少
                BigDecimal price = dto.getPrice();
                Integer quantity = dto.getQuantity();
                String specification = dto.getSpecification();
                String name = dto.getName();

                LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Product::getName, name)
                        .eq(Product::getSpecification, specification);
                Product product = productMapper.selectOne(queryWrapper);
                if(product==null){
                    product = new Product();
                    product.setName(name);
                    product.setSpecification(specification);
                    product.setPrice(price);
                    productMapper.insert(product);
                }

                ServiceOrderProduct serviceOrderProduct = new ServiceOrderProduct();
                serviceOrderProduct.setProductId(product.getId());
                serviceOrderProduct.setServiceOrderId(serviceOrder.getId());

                //总价
                if(quantity!=null && price!=null){
                    BigDecimal totalPrice = price.multiply(BigDecimal.valueOf(quantity));
                    serviceOrderProduct.setPricesTotal(totalPrice);
                }
                serviceOrderProduct.setQuantity(quantity);
                serviceOrderProduct.setCreateTime(Timestamp.valueOf(LocalDateTime.now()));
                serviceOrderProduct.setUpdateTime(Timestamp.valueOf(LocalDateTime.now()));

                serviceOrderProductMapper.insert(serviceOrderProduct);
            }
        }

        // 异步生成 Excel 文件
//        CompletableFuture.runAsync(() -> {
//            try {
//                generateExcelFromServiceOrder(serviceOrderDTO);
//            } catch (Exception e) {
//                log.error("生成 Excel 文件失败: {}", e.getMessage(), e);
//            }
//        });
        //更售后总括表的更新时间
        aUtils.updateServiceOrderUpdateTime(serviceOrderDTO.getServiceOrderNumber());
        return true;
    }


    /**
     * 修改服务单
     * @param serviceOrderDTO
     * @return
     */
    @Override
    @Transactional
    public ResponseResult update(ServiceOrderDTO serviceOrderDTO) {
        ServiceOrder serviceOrder = serviceOrderMapper.selectById(serviceOrderDTO.getId());
        //判断当前状态是否都不满足确认编辑状态，发布之后不可修改
        if(!serviceOrderDTO.getStatus().equals(Status.SERVICE_ORDER_STATUS_EDITING)
                && !serviceOrderDTO.getStatus().equals(Status.SERVICE_ORDER_STATUS_CONFIRMED)){
            log.error("当前状态不能修改");
            return ResponseResult.error("当前状态不能修改");
        }
        //判断当前登陆人是否为创建人
        // 检查是否为创建人
        boolean isCreator = serviceOrder.getCreatedBy().equals(aUtils.getNickNameByuserName(SecurityUtils.getCurrentUsername()));
        // 检查是否具有特殊权限角色
        List<String> currentUserRoles = SecurityUtils.getCurrentUserRoles();
        boolean hasSpecialRole = currentUserRoles.contains(RoleEnum.TECHNICAL_COMMAND.getCode()) ||
                currentUserRoles.contains(RoleEnum.ADMIN.getCode()) ||
                currentUserRoles.contains(RoleEnum.GENERAL_COMMAND.getCode());
        // 只有创建人或具有特殊权限的用户才能修改
        if (!isCreator && !hasSpecialRole) {
            log.error("当前登陆人不是创建人或无权限修改");
            return ResponseResult.error("当前登陆人不是创建人或无权限修改");
        }

        //复制DTO到实体类
        BeanUtils.copyProperties(serviceOrderDTO, serviceOrder);
        //如果不为空获取客户公司名称根据公司名称查询对应公司id
        Long customerCompanyId=null;
        if(serviceOrderDTO.getCustomerCompany() != null){
            customerCompanyId = aUtils.getCustomerCompanyId (serviceOrderDTO.getCustomerCompany());
        }
        //根据传入的客户名称判断是否存在，如果不存在就增加一个联系人
        //在服务单表中插入该联系人的id关联联系人，根据联系人姓名查询联系人id
        String contactPerson = null;
        String phoneNumber = null;
        Long contactPersonId = null;
        if(serviceOrderDTO.getContactPerson() != null){
            contactPerson = serviceOrderDTO.getContactPerson();
            phoneNumber = serviceOrderDTO.getPhoneNumber();
            contactPersonId =aUtils.getcontactPersonId(contactPerson, phoneNumber, customerCompanyId);
        }
        //获取销售经理名称根据名字查询对应的id
        Long salesManagerId = null;
        if(serviceOrderDTO.getSalesManager() != null){
            salesManagerId = aUtils.getUserIdByNickName(serviceOrderDTO.getSalesManager());
        }
        //获取技术对接人名称根据名字查询对应的id
        Long approverUserId = null;
        if(serviceOrderDTO.getTechnicalUser() != null){
            approverUserId = aUtils.getUserIdByNickName(serviceOrderDTO.getTechnicalUser());
        }
        Long technicalUserId =null;
        if(serviceOrderDTO.getTechnicalUser() != null){
            technicalUserId=aUtils.getUserIdByNickName(serviceOrderDTO.getTechnicalUser());
        }
        serviceOrder.setCustomerCompanyId(customerCompanyId);
        serviceOrder.setCustomerContactsId(contactPersonId);
        serviceOrder.setSalesManagerId(salesManagerId);
        serviceOrder.setApproverUserId(approverUserId);
        serviceOrder.setTechnicalUserId(technicalUserId);
        //更新创建人
        serviceOrder.setCreatedBy(SecurityUtils.getCurrentUsername());

        try {
            serviceOrderMapper.updateById(serviceOrder);
        } catch (Exception e) {
            throw new RuntimeException("服务单修改失败");
        }
        //删除中间表信息
        serviceOrderProductMapper.deleteByMap(new HashMap<String, Object>() {{
            put("service_order_id", serviceOrder.getId());
        }});
        //获取中间表信息重新添加
        System.out.println(serviceOrderDTO.getProducts());
            for (ProductDTO dto : serviceOrderDTO.getProducts()) {
                //获取name 规格 单价 数量 没有id
                //获取服务单id
                Long id = serviceOrder.getId();
                //获取设备name
                String name = dto.getName();
                //获取设备规格
                String specification = dto.getSpecification();
                //单价
                BigDecimal price = dto.getPrice();
                //数量
                Integer quantity = dto.getQuantity();
                //计算总价
                BigDecimal totalPrice = null;
                if(price != null && quantity != null){
                    totalPrice = price.multiply(new BigDecimal(quantity));
                }
                ServiceOrderProduct serviceOrderProduct = new ServiceOrderProduct();
                serviceOrderProduct.setServiceOrderId(id);
                serviceOrderProduct.setProductId(aUtils.getProductIdByNameAndSpecification(name, specification));
                serviceOrderProduct.setPricesTotal(totalPrice);
                serviceOrderProduct.setQuantity(quantity);
                serviceOrderProduct.setCreateTime(Timestamp.valueOf(LocalDateTime.now()));
                serviceOrderProduct.setUpdateTime(Timestamp.valueOf(LocalDateTime.now()));
                //存入中间表
                serviceOrderProductMapper.insert(serviceOrderProduct);
            }
        CompletableFuture.runAsync(() -> {
            try {
                generateExcelFromServiceOrder(serviceOrderDTO);
            } catch (Exception e) {
                log.error("更新 Excel 文件失败: {}", e.getMessage(), e);
            }
        });
        aUtils.updateServiceOrderUpdateTime(serviceOrderDTO.getServiceOrderNumber());
        log.info("服务单修改成功修改人:"+SecurityUtils.getCurrentUsername());
        return ResponseResult.success("服务单修改成功");

    }

    /**
     * 根据id查询单个服务单做成vo返回
     * @param id
     * @return
     */
    @Override
    public ServiceOrderVO getById(Long id) {
        // 1. 查询主表数据
        LambdaQueryWrapper<ServiceOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ServiceOrder::getId, id)
                .eq(ServiceOrder::getIsDeleted, 1);
        ServiceOrder serviceOrder = serviceOrderMapper.selectOne(queryWrapper);
        if (serviceOrder == null) {
            throw new RuntimeException("未找到对应服务单");
        }
        // 3. 手动转换 VO
        ServiceOrderVO vo = new ServiceOrderVO();
        //根据公司id查询公司名称
        String customerCompanyName = aUtils.getCustomerCompanyNameById(serviceOrder.getCustomerCompanyId());
        // 根据服务单中的联系人id再去联系人表查询名称和电话
        Long customerContactsId = serviceOrder.getCustomerContactsId();
        if(customerContactsId != null){
            String contactPerson = aUtils.getContactPersonById(customerContactsId);
            String phoneNumber = aUtils.getPhoneNumberById(customerContactsId);
            //联系人姓名电话，根据联系人id查询联系人表
            vo.setContactPerson(contactPerson);
            vo.setPhoneNumber(phoneNumber);
        }
        if(serviceOrder.getSalesManagerId() != null){
            //根据销售经理id查询销售经理名称
            String salesManagerName = aUtils.getUserNickNameByUserId(serviceOrder.getSalesManagerId());
            //销售经理名称
            vo.setSalesManager(salesManagerName);
        }

        if(serviceOrder.getTechnicalUserId() != null){
            //根据technicalUserId查询技术对接人名称
            String technicalUserName = aUtils.getUserNickNameByUserId(serviceOrder.getTechnicalUserId());
            //技术对接人名称
            vo.setTechnicalUser(technicalUserName);
        }

        if(serviceOrder.getApproverUserId() != null){
            //根据approverUserId查询工作量核准人名称
            String approverUserName = aUtils.getUserNickNameByUserId(serviceOrder.getApproverUserId());
            //工作量核准人名称
            vo.setApproverUser(approverUserName);
        }
        vo.setId(serviceOrder.getId());
        // 主表字段赋值
        vo.setServiceOrderNumber(serviceOrder.getServiceOrderNumber());
        //公司名称
        vo.setCustomerCompany(customerCompanyName);
        //服务地点
        vo.setServiceLocation(serviceOrder.getServiceLocation());
        // 预计工作描述
        vo.setExpectedWork(serviceOrder.getExpectedWork());
        // 人员安排
        vo.setStaffArrangement(serviceOrder.getStaffArrangement());
        // 设置状态
        vo.setStatus(serviceOrder.getStatus());
        // 创建人姓名
        vo.setCreatedBy(serviceOrder.getCreatedBy());
        // 根据任务接收人id查询任务接收人姓名去receiver表中查询根据售后编号
        LambdaQueryWrapper<Receiver> receiverQueryWrapper = new LambdaQueryWrapper<>();
        receiverQueryWrapper.eq(Receiver::getOrderNumber, serviceOrder.getServiceOrderNumber());
        List<Receiver> receivers = receiverMapper.selectList(receiverQueryWrapper);
        //创建对应的任务接收人的姓名列表
        // 时间格式化
        DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE;
        vo.setReceiveTime(serviceOrder.getReceiveTime() != null ? serviceOrder.getReceiveTime().format(formatter) : null);
        vo.setConfirmSignDate(serviceOrder.getConfirmSignDate() != null ? serviceOrder.getConfirmSignDate().format(formatter) : null);
        //查询中间表配件数据，再根据中间表的productId查询设备表数据
        List<ProductVO> products = serviceOrderProductMapper.selectByOrderId(serviceOrder.getId());
        LambdaQueryWrapper<ServiceOrderProduct> serviceOrderProductQueryWrapper = new LambdaQueryWrapper<>();
        serviceOrderProductQueryWrapper.eq(ServiceOrderProduct::getServiceOrderId, serviceOrder.getId());
        List<ServiceOrderProduct> serviceOrderProducts = serviceOrderProductMapper.selectList(serviceOrderProductQueryWrapper);
        // 将 total 声明为 BigDecimal，并初始化为零值
        BigDecimal total = BigDecimal.ZERO;

        for (ServiceOrderProduct serviceOrderProduct : serviceOrderProducts) {
            BigDecimal itemTotal = null;

            // 1. 优先使用中间表的总价 pricesTotal
            if (serviceOrderProduct.getPricesTotal() != null) {
                itemTotal = serviceOrderProduct.getPricesTotal();
            }
            // 累加到总金额中 (仅当 itemTotal 不为 null 时)
            if (itemTotal != null) {
                total = total.add(itemTotal); // 使用 BigDecimal 的 add 方法进行累加
            }
        }

        // 设置总价到 VO 对象中
        vo.setTotal(total);

        for (ProductVO product : products) {
            //根据设备单价查询设备总价存入vo
            BigDecimal multiply = product.getPrice().multiply(BigDecimal.valueOf(product.getQuantity()));
            vo.setTotal(vo.getTotal() == null ? multiply : vo.getTotal().add(multiply));
        }
        // 配件列表赋值// 直接使用 MyBatis 返回的 ProductVO 列表
        vo.setProducts(products);
        return vo;
    }

    @Override
    public ServiceOrderVO getByorderNumber(String orderNumber) {
        // 1. 查询主表数据
        LambdaQueryWrapper<ServiceOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ServiceOrder::getServiceOrderNumber, orderNumber)
                    .eq(ServiceOrder::getIsDeleted, 1);
        ServiceOrder serviceOrder = serviceOrderMapper.selectOne(queryWrapper);
        if (serviceOrder == null) {
            return null;
        }
        // 3. 手动转换 VO
        ServiceOrderVO vo = new ServiceOrderVO();
        //根据公司id查询公司名称
        String customerCompanyName = aUtils.getCustomerCompanyNameById(serviceOrder.getCustomerCompanyId());
        // 根据服务单中的联系人id再去联系人表查询名称和电话
        Long customerContactsId = serviceOrder.getCustomerContactsId();
        if(customerContactsId != null){
            String contactPerson = aUtils.getContactPersonById(customerContactsId);
            String phoneNumber = aUtils.getPhoneNumberById(customerContactsId);
            //联系人姓名电话，根据联系人id查询联系人表
            vo.setContactPerson(contactPerson);
            vo.setPhoneNumber(phoneNumber);
        }
        if(serviceOrder.getSalesManagerId() != null){
            //根据销售经理id查询销售经理名称
            String salesManagerName = aUtils.getUserNickNameByUserId(serviceOrder.getSalesManagerId());
            //销售经理名称
            vo.setSalesManager(salesManagerName);
        }

        if(serviceOrder.getTechnicalUserId() != null){
            //根据technicalUserId查询技术对接人名称
            String technicalUserName = aUtils.getUserNickNameByUserId(serviceOrder.getTechnicalUserId());
            //技术对接人名称
            vo.setTechnicalUser(technicalUserName);
        }

        if(serviceOrder.getApproverUserId() != null){
            //根据approverUserId查询工作量核准人名称
            String approverUserName = aUtils.getUserNickNameByUserId(serviceOrder.getApproverUserId());
            //工作量核准人名称
            vo.setApproverUser(approverUserName);
        }
        vo.setId(serviceOrder.getId());
        // 主表字段赋值
        vo.setServiceOrderNumber(serviceOrder.getServiceOrderNumber());
        //公司名称
        vo.setCustomerCompany(customerCompanyName);
        //服务地点
        vo.setServiceLocation(serviceOrder.getServiceLocation());
        // 预计工作描述
        vo.setExpectedWork(serviceOrder.getExpectedWork());
        // 人员安排
        vo.setStaffArrangement(serviceOrder.getStaffArrangement());
        // 设置状态
        vo.setStatus(serviceOrder.getStatus());
        // 创建人姓名
        vo.setCreatedBy(serviceOrder.getCreatedBy());
        // 根据任务接收人id查询任务接收人姓名去receiver表中查询根据售后编号
        LambdaQueryWrapper<Receiver> receiverQueryWrapper = new LambdaQueryWrapper<>();
        receiverQueryWrapper.eq(Receiver::getOrderNumber, serviceOrder.getServiceOrderNumber());
        List<Receiver> receivers = receiverMapper.selectList(receiverQueryWrapper);
        //创建对应的任务接收人的姓名列表
        // 时间格式化
        DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE;
        vo.setReceiveTime(serviceOrder.getReceiveTime() != null ? serviceOrder.getReceiveTime().format(formatter) : null);
        vo.setConfirmSignDate(serviceOrder.getConfirmSignDate() != null ? serviceOrder.getConfirmSignDate().format(formatter) : null);
        //查询中间表配件数据，再根据中间表的productId查询设备表数据
        List<ProductVO> products = serviceOrderProductMapper.selectByOrderId(serviceOrder.getId());
        for (ProductVO product : products) {
            LambdaQueryWrapper<ServiceOrderProduct> qWrapper = new LambdaQueryWrapper<>();
            qWrapper.eq(ServiceOrderProduct::getServiceOrderId, vo.getId());
            qWrapper.eq(ServiceOrderProduct::getProductId, product.getId());
            vo.setTotal(serviceOrderProductMapper.selectOne(qWrapper).getPricesTotal());
            product.setPrice(vo.getTotal().divide(BigDecimal.valueOf(product.getQuantity()), 2, RoundingMode.HALF_UP));
        }
        // 配件列表赋值// 直接使用 MyBatis 返回的 ProductVO 列表
        vo.setProducts(products);
        return vo;
    }

    /**
     * 根据条件分页查询服务单
     * @param pageNum 当前页码
     * @param pageSize 每页显示条数
     * @param customerCompany 客户公司名（用于模糊查询）
     * @param salesManager 销售经理姓名（用于模糊查询）
     * @param serviceOrderNumber 服务单号（用于模糊查询）
     * @param startDate
     * @param endDate
     * @return
     */
    @Override
    public IPage<ServiceOrderVO> getByConditions(Integer pageNum,
                                                 Integer pageSize,
                                                 String customerCompany,
                                                 String salesManager,
                                                 String serviceOrderNumber,
                                                 String startDate, String endDate, String status) {
        // 处理分页参数
        Page<ServiceOrder> page;
        if (pageSize == null) {
            // 查询全部数据，使用足够大的页面大小
            page = new Page<>(1, 100000);
        } else {
            // 正常分页
            page = new Page<>(pageNum, pageSize);
        }

        IPage<ServiceOrderVO> resultPage =
                serviceOrderMapper.getByConditions(page, customerCompany, salesManager, serviceOrderNumber, startDate, endDate, status);
        List<ServiceOrderVO> voList = resultPage.getRecords();

        for (ServiceOrderVO serviceOrderVO : voList) {
            // 根据每一条的订单id查询对应的服务设备中间表数据取出价格和数量 再去设备表取出名称和规格
            List<ProductVO> products = serviceOrderProductMapper.selectByOrderId(serviceOrderVO.getId());
            // 计算总价存入serviceOrderVO中
            products.forEach(productVO -> {
                BigDecimal itemTotal = productVO.getPrice().multiply(BigDecimal.valueOf(productVO.getQuantity()));
                serviceOrderVO.setTotal(
                        serviceOrderVO.getTotal() == null ? itemTotal : serviceOrderVO.getTotal().add(itemTotal)
                );
            });
            serviceOrderVO.setProducts(products);
        }

        // 如果是查询全部，调整分页信息
        if (pageSize == null) {
            resultPage.setPages(1);
            resultPage.setCurrent(1);
            resultPage.setSize(resultPage.getTotal());
        }

        resultPage.setRecords(voList);
        return resultPage;
    }



    /**
     * 根据id删除服务单
     * @param id
     * @return
     */
    @Override
    public boolean delete(Long id) {
        return serviceOrderMapper.deleteById(id) > 0;
    }

    /**
     * 批量删除服务单
     * @param ids
     * @return
     */
    @Override
    public boolean batchDelete(List<Long> ids) {
        return serviceOrderMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 批量逻辑删除
     * @param ids
     * 权限为 管理员 技术指挥部 综合指挥部 及创建者
     * @return
     */
    @Override
    @Transactional
    public ResponseResult isbatchDelete(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            log.warn("批量删除请求为空");
            return ResponseResult.error("批量删除请求为空");
        }

        // 获取当前用户信息
        String currentUsername = aUtils.getNickNameByuserName(SecurityUtils.getCurrentUsername());
        List<String> currentUserRoles = SecurityUtils.getCurrentUserRoles();
        boolean hasSpecialRole = currentUserRoles.contains(RoleEnum.TECHNICAL_COMMAND.getCode()) ||
                currentUserRoles.contains(RoleEnum.ADMIN.getCode()) ||
                currentUserRoles.contains(RoleEnum.GENERAL_COMMAND.getCode());

        //创建一个回收站列表
        List<RecycleBinOrder> recycleRecords = new ArrayList<>();
        //创建一个有效id列表
        List<Long> validIds = new ArrayList<>();

        // 1. 构建回收站记录集合，并检查权限
        for (Long id : ids) {
            log.info("批量删除服务单id为{}", id);
            //查询服务单内容
            ServiceOrder serviceOrder = serviceOrderMapper.selectById(id);
            if(serviceOrder==null){
                continue;
            }

            // 权限检查：当前用户是创建人或者具有特殊权限角色
            boolean isCreator = serviceOrder.getCreatedBy().equals(currentUsername);
            if (!isCreator && !hasSpecialRole) {
                log.error("当前登陆人不是服务单{}的创建人或无权限删除", serviceOrder.getServiceOrderNumber());
                return ResponseResult.error("您没有权限删除服务单：" + serviceOrder.getServiceOrderNumber());
            }

            //判断是否存在下级订单
            if(serviceOrderMapper.getByOrderNumberToDown(serviceOrder.getServiceOrderNumber())){
                //存在则弹出提示提示
                log.warn("存在下级订单，请先删除下级订单");
                return ResponseResult.error("服务单" + serviceOrder.getServiceOrderNumber() + "存在下级订单，请先删除下级订单");
            }
            RecycleBinOrder record = new RecycleBinOrder();
            //设置原始订单id
            record.setOrderId(id);
            //设置订单类型字符串
            record.setOrderType(Status.SERVICE_ORDER);
            //设置删除人
            record.setDeletedBy(currentUsername);
            //设置订单编号
            record.setOrderNumber(serviceOrder.getServiceOrderNumber());
            //设置客户名称
            if(serviceOrder.getCustomerCompanyId()!=null)
                record.setCustomerName(aUtils.getCustomerCompanyNameById(serviceOrder.getCustomerCompanyId()));
            record.setDeleteTime(LocalDateTime.now());
            recycleRecords.add(record);
            validIds.add(id);
        }

        // 2. 批量插入回收站记录
        try {
            recyclebinMapper.batchInsert(recycleRecords);
        } catch (Exception e) {
            log.error("批量插入回收站失败: {}", e.getMessage(), e);
            throw new RuntimeException("回收站记录失败，事务已回滚", e);
        }

        // 3. 执行批量逻辑删除
        try {
            int rowsAffected = serviceOrderMapper.batchSetIsDeleted(validIds);
            if (rowsAffected != validIds.size()) {
                log.warn("逻辑删除数量不一致，预期: {}, 实际: {}", validIds.size(), rowsAffected);
            }
            //4. 删除中间表数据根据当前服务单的id
            serviceOrderProductMapper.deleteBatchByOrderId(validIds);
            if(rowsAffected > 0)
                return ResponseResult.success("批量逻辑删除成功");
            else
                return ResponseResult.error("批量逻辑删除失败");
        } catch (Exception e) {
            log.error("批量逻辑删除失败: {}", e.getMessage(), e);
            throw new RuntimeException("逻辑删除失败，事务已回滚", e);
        }
    }




    /**
     * 修改服务单状态
     * 传入DTO
     * 小程序端：下推，传入id和状态，当前为确认态-下推到进行态，同时生成任务单
     * 权限 为 管理员 技术指挥部 综合指挥部 及创建者才可以下推到下一级
     * @param serviceOrderDTO
     * @return
     */
    @Override
    @Transactional
    public ResponseResult updateStatus(ServiceOrderDTO serviceOrderDTO) throws Exception {
        //根据id查询当前服务单是否存在，若存在则保留数据库中的状态，否则抛出异常表示不存在
        ServiceOrder serviceOrder = serviceOrderMapper.selectById(serviceOrderDTO.getId());
        if(serviceOrder == null||serviceOrder.getIsDeleted()==0){
            return ResponseResult.error("服务单不存在");
        }
        // 权限检查：只有创建者或特定角色可以修改状态
        String currentUsername = aUtils.getNickNameByuserName(SecurityUtils.getCurrentUsername());
        List<String> currentUserRoles = SecurityUtils.getCurrentUserRoles();
        boolean isCreator = serviceOrder.getCreatedBy().equals(currentUsername);
        boolean hasSpecialRole = currentUserRoles.contains(RoleEnum.TECHNICAL_COMMAND.getCode()) ||
                currentUserRoles.contains(RoleEnum.ADMIN.getCode()) ||
                currentUserRoles.contains(RoleEnum.GENERAL_COMMAND.getCode());

        if (!isCreator && !hasSpecialRole) {
            return ResponseResult.error("您没有权限修改服务单状态");
        }

            //获取当前状态
            String status = serviceOrder.getStatus();
            if(Status.SERVICE_ORDER_STATUS_ARCHIVED.equals(status)){
                //如果当前订单已归档，则不允许修改状态抛出异常
                return ResponseResult.error("当前订单已归档，不允许修改状态，请联系管理员处理");
            }
            switch (serviceOrderDTO.getStatus()) {
                //转发布状态
                case Status.SERVICE_ORDER_STATUS_PUBLISHED:
                    //如果为发布状态的前置状态，则正常更新
                    String serviceOrderNumber = serviceOrder.getServiceOrderNumber();
                    if(status.equals(Status.SERVICE_ORDER_STATUS_CONFIRMED)){
                        //rabbitmq下发
                        //通知综合指挥部和技术指挥部
                        //xxx下达了售后服务单
                        //单号：xxx 服务客户：xxx 服务地址：xxx
                        TaskReviewMessageDTO taskReviewMessageDTO = new TaskReviewMessageDTO();
                        //设置当前服务单编号
                        taskReviewMessageDTO.setOrderNumber(serviceOrder.getServiceOrderNumber());
                        taskReviewMessageDTO.setTitle("售后通知单"+serviceOrder.getServiceOrderNumber()+"创建通知");
                        taskReviewMessageDTO.setContent(aUtils.getNickNameByuserName(SecurityUtils.getCurrentUsername())+"创建了服务通知单"+"单号："+serviceOrder.getServiceOrderNumber()+
                                " 服务客户："+aUtils.getCustomerCompanyNameById(serviceOrder.getCustomerCompanyId())+
                                " 服务地址："+serviceOrder.getServiceLocation()+
                                " 预期工作："+serviceOrder.getExpectedWork());
                        taskReviewMessageDTO.setSenderName(aUtils.getNickNameByuserName(SecurityUtils.getCurrentUsername()));
                        taskReviewMessageDTO.setBusinessType(Status.SERVICE_ORDER);
                        //给综合指挥部发送一个消息
                        taskReviewMessageDTO.setRoleName(RoleEnum.GENERAL_COMMAND.getCode());
                        rabbitTemplate.convertAndSend(
                                RabbitMQConstants.EXCHANGE,
                                RabbitMQConstants.ROUTING_KEY_SERVICE_PROBLEM,
                                taskReviewMessageDTO
                        );
                        //给技术指挥部发送一个消息
                        taskReviewMessageDTO.setRoleName(RoleEnum.TECHNICAL_COMMAND.getCode());
                        rabbitTemplate.convertAndSend(
                                RabbitMQConstants.EXCHANGE,
                                RabbitMQConstants.ROUTING_KEY_SERVICE_PROBLEM,
                                taskReviewMessageDTO
                        );
                        //更新当前服务单为已发布
                        serviceOrderMapper.updateStatus(serviceOrderDTO.getId(), Status.SERVICE_ORDER_STATUS_PUBLISHED);
                        //更新售后总括表状态为已发布
                        afterSalesMapper.updateStatusByOrderNumber(serviceOrderNumber, Status.SERVICE_ORDER_STATUS_PUBLISHED);
                        serviceOrder.setStatus(Status.SERVICE_ORDER_STATUS_PUBLISHED);
                        //调用新增任务单和确认单的方法
                        if(addtaskorder(serviceOrder,serviceOrderDTO.getReceiverName()))
                            return ResponseResult.success("更新成功");
                    }
                    //如果为后置状态，则只把状态更新为发布中
                    else if(status.equals(Status.SERVICE_ORDER_STATUS_PROCESSING)){
                        //如果改为发布中，那之前生成的任务单怎么处理？留着？还是重新生成？还是去判断任务单是否存在？
                        //还是去删除任务单才能回退？肯定是需要去判断任务单是否存在的，那到任务单这一节，应该删除吗？
                        //判断任务单是否存在，存在则抛出异常提示当前任务单存在请先删除任务单，不存在则继续执行
                        //拿到当前服务单单号=任务单单号
                        String taskOrderNumber = serviceOrder.getServiceOrderNumber();
                        //查询任务单表是否存在该单号的数据，如果存在，则返回错误，不存在则继续执行
                        if(taskorderMapper.selectIdByOrderNumber(taskOrderNumber)!=null){
                            return ResponseResult.error("任务单存在请先删除任务单");
                        }
                        else{
                            if(serviceOrderDTO.getReceiverName()!=null){
                                //根据名称列表查询接收人ids
                                List<Long> receiverIdsByName = aUtils.getUserIdsByNickName(serviceOrderDTO.getReceiverName());
                                //遍历ids列表存入receiver中间表中
                                for (Long aLong : receiverIdsByName) {
                                    Receiver receiver = new Receiver();
                                    receiver.setUserId(aLong);
                                    receiver.setOrderNumber(serviceOrderNumber);
                                    receiverMapper.insert(receiver);
                                }
                            }
                            serviceOrderMapper.updateStatus(serviceOrderDTO.getId(), Status.SERVICE_ORDER_STATUS_PUBLISHED);
                            //调用新增任务单和确认单的方法
                            if(addtaskorder(serviceOrder,serviceOrderDTO.getReceiverName()))
                                return ResponseResult.success("更新成功");
                        }
                    }
                    return ResponseResult.error("修改状态失败");
                default:
                    return ResponseResult.error("修改状态失败，请联系管理员处理");
            }

    }

    //生成任务单方法
    //不需要在这时候生成确认单，而是在下推任务单的时候去生成确认单
    @Transactional
    public boolean addtaskorder(ServiceOrder serviceOrder,List<String> receiverNames) {
        //获取服务单号 联系人id 销售经理id 技术负责人id 客户公司id
        String serviceOrderNumber = serviceOrder.getServiceOrderNumber();
        Long customerContactsId = serviceOrder.getCustomerContactsId();
        Long salesManagerId = serviceOrder.getSalesManagerId();
        Long technicalUserId = serviceOrder.getTechnicalUserId();
        Long customerCompanyId = serviceOrder.getCustomerCompanyId();
        TaskOrderDTO taskOrderDTO = new TaskOrderDTO();
        //分别设置任务单单号 客户公司名称 联系人名称 业务经理名称 技术负责人名称
        taskOrderDTO.setTaskOrderNumber(serviceOrderNumber);
        if(customerCompanyId!= null)
        taskOrderDTO.setCustomerCompanyName(aUtils.getCustomerCompanyNameById(customerCompanyId));
        if(customerContactsId != null)
        taskOrderDTO.setContactPersonName(aUtils.getContactPersonById(customerContactsId));
        if(customerContactsId != null)
        taskOrderDTO.setPhoneNumber(aUtils.getPhoneNumberById(customerContactsId));
        if(salesManagerId!= null)
        taskOrderDTO.setBusinessManagerName(aUtils.getUserNickNameByUserId(salesManagerId));
        if(technicalUserId!= null)
        taskOrderDTO.setTechnicalManagerName(aUtils.getUserNickNameByUserId(technicalUserId));
        taskOrderDTO.setReceiverName(receiverNames);
        taskOrderDTO.setStatus(serviceOrder.getStatus());
        taskOrderDTO.setCreatedBy(aUtils.getNickNameByuserName(SecurityUtils.getCurrentUsername()));
        //根据任务接收人id查询接收人姓名
        //taskOrderDTO.setReceiverName(aUtils.getUserNameByUserId(serviceOrder.getReceiverId()));
        if (!taskorderService.add(taskOrderDTO)) {
            throw new RuntimeException("任务单生成失败");
        }
//        //在生成任务单同时还需要生成一份确认单
//        ConfirmationOrder confirmationOrder = new ConfirmationOrder();
//        //填入三表相同的服务单号
//        confirmationOrder.setTaskOrderNumber(serviceOrderNumber);
//        //查询前面的任务单id
//        Long taskid = taskorderMapper.selectIdByOrderNumber(serviceOrderNumber);
//        confirmationOrder.setTaskOrderId(taskid);
//        if(!confirmationService.add(confirmationOrder)){
//            throw new RuntimeException("确认单生成失败");
//        }
        return true;
    }

    private ServiceOrderVO convertToVO(ServiceOrder order) {
        ServiceOrderVO vo = new ServiceOrderVO();
        BeanUtils.copyProperties(vo, order);

        // 公司信息
        vo.setCustomerCompany(aUtils.getCustomerCompanyNameById(order.getCustomerCompanyId()));

        // 联系人信息
        if (order.getCustomerContactsId() != null) {
            vo.setContactPerson(aUtils.getContactPersonById(order.getCustomerContactsId()));
            vo.setPhoneNumber(aUtils.getPhoneNumberById(order.getCustomerContactsId()));
        }

        // 用户信息
        vo.setSalesManager(aUtils.getUserNickNameByUserId(order.getSalesManagerId()));
        vo.setTechnicalUser(aUtils.getUserNickNameByUserId(order.getTechnicalUserId()));
        vo.setApproverUser(aUtils.getUserNickNameByUserId(order.getApproverUserId()));

        // 时间格式化
        DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE;
        vo.setReceiveTime(order.getReceiveTime() != null ? order.getReceiveTime().format(formatter) : null);
        vo.setConfirmSignDate(order.getConfirmSignDate() != null ? order.getConfirmSignDate().format(formatter) : null);

        // 配件信息
        vo.setProducts(serviceOrderProductMapper.selectByOrderId(order.getId()));

        return vo;
    }



    /**
     * 生成excel方法
     * @param serviceOrderDTO
     * @throws Exception
     */
    private void generateExcelFromServiceOrder(ServiceOrderDTO serviceOrderDTO) throws Exception{
        String templatePath = "E:\\plm\\modelfeil\\服务通知单模板.xlsx"; // 模板文件路径
        // 1. 构建基础文件名（不含后缀）
        String baseFileName = serviceOrderDTO.getServiceOrderNumber()
                + serviceOrderDTO.getCustomerCompany()
                + "服务通知单.xlsx";
        String outputPath = "E:\\plm\\modelfeil\\" + baseFileName;

        // 2. 检查文件是否已存在
        File outputFile = new File(outputPath);
        int counter = 1;
        String fileNameWithoutExt = baseFileName.replace(".xlsx", "");

        // 3. 若存在，添加递增数字后缀（最多尝试99次）
        while (outputFile.exists() && counter <= 99) {
            outputPath = String.format("e:\\plm\\modelfeil\\%s_%d.xlsx", fileNameWithoutExt, counter);
            outputFile = new File(outputPath);
            counter++;
        }

        if (counter > 99) {
            throw new RuntimeException("无法生成文件：超过最大重试次数");
        }
        //摘出字段值
        //服务单号
        String serviceOrderNumber = serviceOrderDTO.getServiceOrderNumber();
        //接收时间转为字符串2024/12/1
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        LocalDate date = LocalDate.parse(serviceOrderDTO.getReceiveTime(), formatter);
        LocalDateTime receiveTime = date.atStartOfDay(); // 或者根据业务需要设置具体时间
        String receiveTimeStr = receiveTime.getYear()+"/"+receiveTime.getMonthValue()+"/"+receiveTime.getDayOfMonth();
        //客户公司名称
        String customerCompanyName = serviceOrderDTO.getCustomerCompany();
        //联系人姓名电话
        String contactPerson = serviceOrderDTO.getContactPerson();
        String phoneNumber = serviceOrderDTO.getPhoneNumber();
        //销售经理姓名
        String salesManagerName = serviceOrderDTO.getSalesManager();
        //服务地点
        String serviceLocation = serviceOrderDTO.getServiceLocation();
        //技术对接人姓名
        String technicalUserName = serviceOrderDTO.getTechnicalUser();
        //工作量核准人员姓名
        String approverUserName = serviceOrderDTO.getApproverUser();
        //预期工作描述
        String expectedWork = serviceOrderDTO.getExpectedWork();
        //人员安排
        String staffArrangement = serviceOrderDTO.getStaffArrangement();
        //设备列表
        ProductDTO[] productDTOS = serviceOrderDTO.getProducts();
        //遍历设备列表，计算总价
        BigDecimal totalPrice= new BigDecimal(0);
        try (FileInputStream fis = new FileInputStream(templatePath);
             Workbook workbook = new XSSFWorkbook(fis)) {
            Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
            for (Row row : sheet) {
                for (Cell cell : row) {
                    if (cell.getCellType() == CellType.STRING) {
                        String cellValue = cell.getStringCellValue();
                        if (cellValue.contains("B2")) {
                            cell.setCellValue(cellValue.replace("B2", serviceOrderNumber));
                        }else if (cellValue.contains("B3")) {
                            cell.setCellValue(cellValue.replace("B3", receiveTimeStr));
                        } else if (cellValue.contains("B4")) {
                            cell.setCellValue(cellValue.replace("B4", customerCompanyName));
                        } else if (cellValue.contains("B5")) {
                            cell.setCellValue(cellValue.replace("B5", contactPerson+" "+phoneNumber));
                        } else if (cellValue.contains("D5")) {
                            cell.setCellValue(cellValue.replace("D5", salesManagerName));
                        } else if (cellValue.contains("B6")) {
                            cell.setCellValue(cellValue.replace("B6", serviceLocation));
                        } else if (cellValue.contains("B7")) {
                            cell.setCellValue(cellValue.replace("B7", technicalUserName));
                        } else if (cellValue.contains("D7")) {
                            cell.setCellValue(cellValue.replace("D7", approverUserName));
                        }else if (cellValue.contains("B8")) {
                            cell.setCellValue(cellValue.replace("B8", expectedWork));
                        }else if (cellValue.contains("B9")) {
                            cell.setCellValue(cellValue.replace("B9", staffArrangement));
                        }
                    }
                }
            }
             //获取配件的数据条数
            int length = productDTOS.length;

            // 配件起始行号（假设从第 10 行开始）
            int startRow = 10;

            // 判断配件数据的条数，如果数据条数大于 4 条，则需要动态插入新行
            for (int i = 0; i < length; i++) {
                ProductDTO productDTO = productDTOS[i];
                String name = productDTO.getName();
                String specification = productDTO.getSpecification();
                Integer quantity = productDTO.getQuantity();
                BigDecimal price = productDTO.getPrice();

                // 计算单个配件的总价并累加到总价格中
                BigDecimal singleTotalPrice = price.multiply(new BigDecimal(quantity));
                totalPrice = totalPrice.add(singleTotalPrice);

                // 动态计算当前行号
                int currentRowNum = startRow + i;

                // 如果当前行不存在，则创建新行，并将后续行下移
                if (i >= 4) {
                    sheet.shiftRows(currentRowNum, sheet.getLastRowNum(), 1); // 下移一行
                }
                Row currentRow = sheet.getRow(currentRowNum);
                if (currentRow == null) {
                    currentRow = sheet.createRow(currentRowNum); // 创建新行
                }
                // 创建字体样式
                Font font = workbook.createFont();
                font.setFontName("等线"); // 设置字体名称
                font.setFontHeightInPoints((short) 12); // 设置字体大小
                // 创建单元格样式并应用字体
                CellStyle cellStyle = workbook.createCellStyle();
                cellStyle.setFont(font);
                // 设置四周框线
                cellStyle.setBorderTop(BorderStyle.THIN); // 上边框
                cellStyle.setBorderBottom(BorderStyle.THIN); // 下边框
                cellStyle.setBorderLeft(BorderStyle.THIN); // 左边框
                cellStyle.setBorderRight(BorderStyle.THIN); // 右边框
                //设置居中
                cellStyle.setAlignment(HorizontalAlignment.CENTER);
                cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
                // 填充配件信息到对应的列
                currentRow.createCell(1).setCellValue(name);
                currentRow.getCell(1).setCellStyle(cellStyle);
                currentRow.createCell(2).setCellValue(specification);
                currentRow.getCell(2).setCellStyle(cellStyle);
                currentRow.createCell(3).setCellValue(quantity);
                currentRow.getCell(3).setCellStyle(cellStyle);
                currentRow.createCell(4).setCellValue(price.doubleValue());
                currentRow.getCell(4).setCellStyle(cellStyle);
            }
            sheet.getRow(length+13).getCell(4).setCellValue(totalPrice.doubleValue());
            //设置制表时间为mmmm年yy月dd日
            String tabulationTime = receiveTime.getYear()+"年"+receiveTime.getMonthValue()+"月"+receiveTime.getDayOfMonth()+"日";
            sheet.getRow(length-4+26).getCell(2).setCellValue(tabulationTime);
            // 将填充后的文件保存到输出路径
            try (FileOutputStream fos = new FileOutputStream(outputPath)) {
                workbook.write(fos);
            }
            catch (Exception e) {
                throw new RuntimeException("生成Excel文件失败");
            }
        }
    }

    /**
     * 恢复订单
     * @param orderId
     * @return
     */
    @Override
    public boolean restoreOrderById(Long orderId) {
        //设置isdelete为1 恢复数据
        ServiceOrder serviceOrder = new ServiceOrder();
        serviceOrder.setIsDeleted(1);
        return serviceOrderMapper.update(serviceOrder, new LambdaQueryWrapper<ServiceOrder>().eq(ServiceOrder::getId, orderId)) > 0;
    }

    /**
     * 彻底删除订单
     * @param orderId
     * @return
     */
    @Override
    public boolean deleteOrderById(Long orderId) {
        return serviceOrderMapper.deleteById(orderId) > 0;
    }
}
